package siwi.map.android;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.wmw.Animation.ViewAction;
import com.wmw.DataPool.CommonData;
import com.wmw.Utility.Common;
import com.wmw.Utility.Dish;
import com.wmw.Utility.MSG;
import com.wmw.Utility.RegularExpression;
import com.wmw.music.Constant;
import com.wmw.music.MediaPlayerService;
import com.wmw.music.MusicData;
import com.wmw.music.Util;
import com.wmw.music.AllMusicMessage;

public class PersonalCenter extends SherlockActivity {
	// 超大和极小的图片会有什么现象.
	private final static int _ImmediateRing = 0;
	private final static int _DelayRing = 1;

	private final static int _TakeAPhotograph = 0;
	private final static int _SelectAphotograph = 1;
	private final static int _CutOutPhotograph = 2;
	TextView _immediateRingName, _delayRingName;
	ImageView _playImmediateRingName;
	int _curPlayingIdx;
	boolean _bPlaying;
	String[] musicNames;

	InputBox _realName;

	private ImageView _avatar;
	private int _avatarWidth, _avatarHeigth;
	private File file;
	private Bitmap tmpPhoto;
	private Bitmap _photo;
	String DATA = MediaStore.Audio.Media.DATA;
	String TITLE = MediaStore.Audio.Media.TITLE;
	String DURATION = MediaStore.Audio.Media.DURATION;
	String ARTIST_ID = MediaStore.Audio.Media.ARTIST_ID;
	String ALBUM_ID = MediaStore.Audio.Media.ALBUM_ID;
	String YEAR = MediaStore.Audio.Media.YEAR;

	String ARTIST = MediaStore.Audio.Media.ARTIST;
	String ALBUM = MediaStore.Audio.Media.ALBUM;

	Uri uri_meta = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
	Intent _playMusicIntent;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initActionBar();

		Log.d(Common.GetLineInfo(), "-" + getIntent().getExtras());
		setContentView(R.layout.personal_center);

		initViews();
		initData();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(Common.GetLineInfo(), "requestCode -" + requestCode + ", resultCode -" + resultCode);

		if (resultCode == RESULT_OK) {
			destoryImage();
			
			if (requestCode == _TakeAPhotograph) {
				Log.d(Common.GetLineInfo(), "-");
				if (file != null && file.exists()) {
					Log.d(Common.GetLineInfo(), "-");
					BitmapFactory.Options option = new BitmapFactory.Options();
					option.inSampleSize = 2;
					
					_photo = BitmapFactory.decodeFile(file.getPath(), option);
					_avatar.setImageBitmap(_photo);
					
					Intent intent = new Intent(PersonalCenter.this, CropImage.class);
					startActivityForResult(intent, _CutOutPhotograph);
					Common.saveBitmap(_photo);
				}
			} else if (requestCode == _CutOutPhotograph) {
				BitmapFactory.Options option = new BitmapFactory.Options();
				option.inSampleSize = 2;
				_photo = BitmapFactory.decodeFile(file.getPath(), option);
				_avatar.setImageBitmap(_photo);
			} else if (requestCode == _SelectAphotograph){
				ContentResolver resolver = getContentResolver();
				//照片的原始资源地址
				Uri originalUri = data.getData(); 
	            try {
	            	//使用ContentProvider通过URI获取原始图片
					Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					if (photo != null) {
//						//为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
//						Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
//						//释放原始图片占用的内存，防止out of memory异常发生
//						photo.recycle();
						_photo = photo;
						_avatar.setImageBitmap(photo);
						Common.saveBitmap(photo);
					}
				} catch (FileNotFoundException e) {
				    e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		else if (requestCode == _CutOutPhotograph){
			//TODO
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		return new AlertDialog.Builder(PersonalCenter.this)
				.setTitle("")
				.setItems(R.array.PictureSelection,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO
								String[] items = getResources().getStringArray(
										R.array.PictureSelection);
								Log.d(Common.GetLineInfo(), "You selected: "
										+ which + " , " + items[which]);
								switch(which){
								case _TakeAPhotograph:
									loadCamera();
									break;
								case _SelectAphotograph:
									Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
									openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
									startActivityForResult(openAlbumIntent, _SelectAphotograph);
									break;
								}
							}
						}).create();
	}
	
	private void initActionBar() {
		// Custom action bar.
		ActionBar actionBar = getSupportActionBar();
		ActionBar.LayoutParams params = new ActionBar.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
				Gravity.CENTER);
		View view = LayoutInflater.from(this).inflate(
				R.layout.action_bar_back_save, null);
		actionBar.setCustomView(view, params);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);

		TextView tv = (TextView) view.findViewById(R.id.ABBS_Title);
		tv.setText("个人中心");

		findViewById(R.id.ABBS_Back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewAction.startSpringMenuAnimations(v);
				// Go back.
				Log.d(Common.GetLineInfo(), "Go back without saving");
				goBack();
				return;
			}
		});

		findViewById(R.id.ABBS_Save).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewAction.startSpringMenuAnimations(v);
				if (!_realName.isValide()) {
					Toast.makeText(PersonalCenter.this, "请输入您的真实姓名",
							Toast.LENGTH_SHORT).show();
					return;
				}

				// TODO
				Common.toastInfo(PersonalCenter.this, "通知修改店主姓名");

				ExApplication app = (ExApplication) getApplication();
				CommonData data = app._Data;
				data.set_realName(_realName.getContent());

				Log.d(Common.GetLineInfo(), "Go back and saving");
				overridePendingTransition(R.anim.left_in, R.anim.right_out);

				finish();
				return;
			}

		});
	}

	private void destoryImage() {
		if (_photo != null) {
			_photo.recycle();
			_photo = null;
		}
	}

	private void loadCamera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			file = new File(Common._SDPath, Common._BitmapName);
			file.delete();
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					Toast.makeText(PersonalCenter.this, "照片创建失败!",
							Toast.LENGTH_LONG).show();
					return;
				}
			}
			Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
			startActivityForResult(intent, _TakeAPhotograph);
		} else {
			Toast.makeText(PersonalCenter.this, "sdcard无效或没有插入!",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void initViews() {
		File savePath = new File(Common._SDPath);
		if (!savePath.exists()) {
			savePath.mkdirs();
		}

		_avatar = (ImageView) findViewById(R.id.PC_Avatar);
		_avatar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showDialog(0);
			}
		});
	}

	private void initData() {
		ExApplication app = (ExApplication) getApplication();
		CommonData appData = app._Data;

		// User name.
		TextView tvUsername = (TextView) findViewById(R.id.PC_Username);
		tvUsername.setText(appData.get_username());

		// Real name.
		final EditText etRealName = (EditText) findViewById(R.id.PC_RealName);
		ImageView ivClearRealName = (ImageView) findViewById(R.id.PC_ClearRealName);
		etRealName.setText(appData.get_realName());
		_realName = new InputBox(PersonalCenter.this, etRealName,
				ivClearRealName, null, etRealName.getPaddingRight(),
				RegularExpression.RealName, new InputBox.ShakeBox() {
					@Override
					public void Action(EditText et, String regularExpression,
							Context context, View v, boolean hasFocus) {
						super.Action(et, regularExpression, context, v,
								hasFocus);
					}

					@Override
					public void OnFocusChange(boolean valide, boolean hasFocus) {
						super.OnFocusChange(valide, hasFocus);
						Log.d(Common.GetLineInfo(), "Focus -" + hasFocus);
						if (hasFocus)
							etRealName.setBackgroundColor(getResources()
									.getColor(R.color.TextBackground));
						else {
							etRealName.setBackgroundColor(getResources()
									.getColor(R.color.Transparent));
						}
					}
				});

		// Store name.
		final EditText etStoreName = (EditText) findViewById(R.id.PC_CurrentStoreName);
		etStoreName.setText(appData.get_storeName());
		
		_avatarWidth = _avatar.getWidth();
		_avatarHeigth = _avatar.getHeight();
		Log.d(Common.GetLineInfo(), "width -" + _avatarWidth + ", height -" + _avatarHeigth);
	}

	private void goBack() {
		Intent intent = new Intent();
		intent.setClass(PersonalCenter.this, Home.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(intent);
		overridePendingTransition(R.anim.left_in, R.anim.right_out);
		PersonalCenter.this.finish();
	}

}
